# @time     :2022/1/19
# @Author   :Simple
# @FileName :yaml
import collections
import os
from string import Template

import yaml

from util.config import CONFIG_, cases_path
from util.config import BASE_DIR
from util.logger import log as logger, log


def load_test_case(path, data_key):
    """
    加载yaml文件中测试用例数据和ids
    :param path: 测试用例文件名
    :param data_key: 数据名
    :return:
    """
    path = os.path.join(cases_path, path)
    with open(path) as f:
        cases = yaml.safe_load(f)
    return cases[data_key]["data"], cases[data_key]["id"]


def read_yaml(file):
    """
    读取yaml文件
    :param file: 文件绝对路径或相对项目根目录的路径
    :return:
    """
    if not file.startswith("/"):
        file = "/" + file
    if BASE_DIR not in file:
        file = BASE_DIR + "/" + file
    if not os.path.exists(file):
        logger.warning(f"{file}文件不存在")
        raise FileNotFoundError
    with open(file, 'r', encoding="utf-8") as f:
        return yaml.safe_load(f)


def get_config_():
    """
    获取配置文件内容
    """
    base_caps = read_yaml(CONFIG_)
    return base_caps


def template(file, data):
    """
    给请求添加参数
    :param file: 文件绝对路径或相对项目根目录的路径
    :param data:
    :return:
    """
    if not file.startswith("/"):
        file = "/" + file
    if BASE_DIR not in file:
        file = BASE_DIR + file
    with open(file, encoding="utf-8") as f:
        return yaml.safe_load(Template(f.read()).safe_substitute(data))


def get_api(file, data):
    """
    获取api信息，已匹配data数据，去掉None的参数
    :param file: 文件绝对路径或相对项目根目录的路径
    :param data:
    :return:
    """
    api_json = template(file, data)
    if api_json.get("json") is not None:
        keys = list(api_json['json'].keys())
        for key in keys:
            value = api_json['json'][key]
            if isinstance(value, int):
                value = str(value)
            if not value or "$" in value:
                api_json['json'].pop(key)
        if len(api_json.get("json")) == 0:
            api_json.pop("json")
    if api_json.get("params") is not None:
        keys = list(api_json['params'].keys())
        for key in keys:
            value = api_json['params'][key]
            if isinstance(value, int):
                value = str(value)
            if not value or "$" in api_json['params'][key]:
                api_json['params'].pop(key)
        if len(api_json.get("params")) == 0:
            api_json.pop("params")
    log.info(f"api_request: {api_json}")
    return api_json


def pre_api(response: dict, pre_param: str):
    """
    从response中按pre_param规则提取数据
    :param response:
    :param pre_param: 提取规则
    例如 从{"name1":{"name2":{"name3":"value3"}}}中提取"value3"，则pre_param为"name1.name2.name3"
    :return:
    """
    new_response = response
    keys = pre_param.split(".")
    if len(keys) < 1:
        log.warnning(f" {pre_param} 为空，提取数据失败")
        return
    try:
        for i in range(len(keys)):
            response = response[keys[i]]
        log.debug(f" {new_response} 提取数据 {pre_param} 成功！")
        return response
    except:
        log.warnning(f" {new_response} 提取数据 {pre_param} 失败！")
        return


# if __name__ == "__main__":
    # file = "api/user/user_create.yml"
    # data = {"access_token": "access_token", "userid": "zhangsan", "name": "var1", "department": ["1"]}
    # print(template(file, data))
#     f = get_api(file, user)
#     r = requests.request(**f).json()
#     print(f"response: {r}")
